<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\api\House;
use App\Models\api\IntermediaryUser;
use Illuminate\Http\Request;
use App\Service\Phone;
use App\Service\Token;
use App\Service\Curl;
use Illuminate\Support\Facades\Cache;
use Elasticsearch\ClientBuilder;

class AgentLoginController extends Controller
{
    //微信小程序登录
    public function wxLogin(Request $request)
    {
        $params = $request->post();
        $captcha = Cache::get($params['mobile'].'_code');
        if ($captcha != $params['code1']){
            Cache::get($params['mobile'].'_code',null);
            return ['code'=>403,'msg'=>'验证码错误','data'=>[]];
        }else{
            $user = IntermediaryUser::where('mobile',$params['mobile'])->first();
            //生成token
            $token = (new Token())->createToken($user->id);
            $stdData = [
                'code' => 200,
                'msg' => '操作成功',
                'token' => $token
            ];
            return json_encode($stdData);
        }
    }

    //微信发送验证码
    public function sendCode(Request $request)
    {
        $phone = $request->get('mobile');

        if(empty($phone)){
            return ['code'=>10001, 'msg' => '手机号不能为空', 'data'=> []];
        }
        $cache = Cache::get($phone.date("Y:m:d"));
        if($cache > 5){
            return ['code' => 10003, 'msg' => '每天只能发送五条短信', 'data' => []];
        }
        $captcha = (new Phone())->sendSms($phone);
        Cache::put($phone,$captcha,60*15);
        $num = $cache + 1;
        Cache::put($phone.date("Y:m:d"),$num,60*60*24);
        return ['code' => 200, 'msg' => '短信发送成功', 'data' => $captcha];
    }

    public function wxGrant(Request $request)
    {
        $params = $request->post();
        $nickname = $request->post('nickname');
        $avatar = $request->post('avatar');
        $stdData = array();
        //获取code码
        $code = $request->get('code');
        //获取微信授权url
        $url = sprintf(config('wx.wxLoginUrl'),config('wx.AppID'),config('wx.AppSecret'),$code);
        //获取openid
        $data = Curl::getCurl($url);
        //查询数据表中是否有数据  若没有 则新增
        $user = IntermediaryUser::where('openid',$data['openid'])->first();
        //若表中没有数据则添加openid进数据库
        if(empty($user)){
            $user = IntermediaryUser::create(['openid'=>$data['openid'],'session_key'=>$data['session_key'],
                'mobile'=>$params['mobile'],'nickname'=>$nickname,'avatar'=>$avatar]);
        }
        //生成token
        $token = (new Token())->createToken($user->id);
        $stdData = [
            'code' => 200,
            'msg' => '操作成功',
            'token' => $token
        ];
        return json_encode($stdData);
    }

}
